<template>
	<div>
		<!-- 使用teleport确保对话框在body下，避免嵌套问题 -->
		<el-dialog
			v-model="visible"
			:title="'选择转发对象'"
			:width="500"
			:append-to-body="true"
			:destroy-on-close="false"
			:close-on-click-modal="false"
			@closed="onCancel">
			<template #default>
				<div class="chat-forward-container">
					<div class="forward-header">
						<el-input 
							placeholder="搜索" 
							prefix-icon="el-icon-search"
							v-model="searchText"
							clearable
							size="small">
						</el-input>
						<div class="forward-actions">
							<el-button size="small" type="warning" @click="onClean">清空</el-button>
							<el-button size="small" type="primary" @click="onOk" :disabled="select.length === 0">
								发送({{select.length}})
							</el-button>
						</div>
					</div>

					<div v-if="select.length > 0" class="selected-items">
						<div v-for="(m, index) in select" :key="index" class="selected-item">
							<head-image :name="m.showName" :url="m.headImage" :size="40"></head-image>
							<span class="selected-name">{{m.showName}}</span>
						</div>
					</div>

					<div class="forward-title">
						<span>最近聊天</span>
						<el-button type="text" @click="onNewChat">创建新会话</el-button>
					</div>

					<div class="chat-list">
						<el-scrollbar style="height: 350px">
							<div v-for="(item, index) in filteredChats" :key="index" class="chat-item" @click="onSwitchChecked(item)">
								<head-image :name="item.showName" :url="item.headImage" :size="40"></head-image>
								<div class="chat-info">
									<div class="chat-name">{{item.showName}}</div>
								</div>
								<el-checkbox v-model="item.checked"></el-checkbox>
							</div>
							<div v-if="filteredChats.length === 0" class="empty-data">
								<span>暂无数据</span>
							</div>
						</el-scrollbar>
					</div>
				</div>
			</template>
		</el-dialog>
		
		<!-- 调试用显示器，看对话框是否打开 -->
		<div v-if="visible" class="debug-indicator">
			对话框已打开 (visible = {{visible}})
		</div>
	</div>
</template>

<script>
	import friendApi from '../../api/im/friend';
	import { mapState } from 'vuex'; // 添加Vuex辅助函数
	import HeadImage from '../common/HeadImage.vue';

	export default {
		name: "ChatForward",
		components: {
			HeadImage
		},
		props: {
			ownerId: {
				type: String,
			}
		},
		data() {
			return {
				visible: false,
				searchText: "",
				showMembers: [],
				select: [],
				dataList: [],
				current: 0,
				total: 0,
				currentPage: 1,
				pageSize: 20,
				fallbackVisible: false // 备用方案可见性控制
			};
		},
		mounted() {
			// 无需立即加载
		},
		methods: {
			loadData() {
				try {
					console.log('加载聊天数据');
					if (this.chats && this.chats.length > 0) {
						// 从store获取聊天列表并拷贝一份
						this.dataList = JSON.parse(JSON.stringify(this.chats)).map(chat => {
							chat.checked = false;
							return chat;
						});
						console.log('获取到聊天列表:', this.dataList.length);
					} else {
						console.warn('聊天列表为空');
						this.dataList = [];
					}
				} catch (error) {
					console.error('加载数据失败:', error);
				}
			},
			onNewChat() {
				this.visible = false;
				// 如需实现，可在这里添加创建新会话的逻辑
				// this.$refs.mailList.open();
			},
			sendChat(select) {
				//发送消息
				setTimeout(() => {
					this.$emit("complete", select);
					this.visible = false;
				}, 100);
			},
			init() {
				try {
					console.log('初始化转发组件');
					this.select = [];
					this.loadData();
					this.onClean();
				} catch (error) {
					console.error('初始化转发组件失败:', error);
				}
			},
			open() {
				console.log('打开转发对话框, 当前visible值:', this.visible);
				this.visible = true;
				this.init();
				console.log('设置visible为true后:', this.visible);
				
				// 强制视图更新并确保对话框显示
				this.$nextTick(() => {
					console.log('nextTick中visible值:', this.visible);
					// 添加消息通知，确认对话框应该显示
					this.$message({
						message: '选择要转发的联系人',
						type: 'info',
						duration: 2000
					});
					
					// 如果对话框仍然不显示，尝试使用备用方法
					setTimeout(() => {
						if (!document.querySelector('.el-dialog__wrapper')) {
							console.log('对话框未显示，尝试备用方案');
							this.showFallbackDialog();
						}
					}, 500);
				});
			},
			onCancel() {
				this.visible = false;
			},
			onSwitchChecked(item) {
				item.checked = !item.checked;
				this.updateSelection();
			},
			updateSelection() {
				this.select = this.dataList.filter(item => item.checked);
			},
			onClean() {
				this.dataList.forEach(item => {
					item.checked = false;
				});
				this.select = [];
			},
			onOk() {
				if (this.select.length === 0) {
					return;
				}
				
				this.$emit("complete", this.select);
				this.visible = false;
			},
			
			// 备用方案：使用MessageBox作为临时解决方案
			showFallbackDialog() {
				this.fallbackVisible = true;
				this.$confirm('选择转发对象', {
					confirmButtonText: '发送',
					cancelButtonText: '取消',
					type: 'info',
					showCancelButton: true,
					customClass: 'forward-fallback-dialog',
					beforeClose: (action, instance, done) => {
						if (action === 'confirm' && this.select.length > 0) {
							this.$emit("complete", this.select);
						}
						done();
					}
				}).then(() => {
					// 确认按钮
					console.log('确认发送');
				}).catch(() => {
					// 取消按钮
					console.log('取消发送');
				}).finally(() => {
					this.fallbackVisible = false;
				});
			}
		},
		computed: {
			...mapState({
				storeChats: state => state.chatStore.chats
			}),
			chats() {
				// 从Vuex store获取聊天列表
				return this.storeChats || [];
			},
			filteredChats() {
				if (!this.dataList) return [];
				if (!this.searchText) return this.dataList;
				
				return this.dataList.filter(item => 
					item.showName && item.showName.toLowerCase().includes(this.searchText.toLowerCase())
				);
			}
		}
	}
</script>

<style lang="scss" scoped>
.chat-forward-container {
	display: flex;
	flex-direction: column;
	width: 100%;
	
	.forward-header {
		display: flex;
		margin-bottom: 15px;
		
		.el-input {
			flex: 1;
			margin-right: 10px;
		}
		
		.forward-actions {
			display: flex;
			
			.el-button {
				margin-left: 5px;
			}
		}
	}
	
	.selected-items {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 15px;
		padding: 8px;
		background: #f5f7fa;
		border-radius: 4px;
		
		.selected-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin: 5px 10px;
			
			.selected-name {
				margin-top: 5px;
				font-size: 12px;
				max-width: 60px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
	}
	
	.forward-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		
		span {
			font-size: 14px;
			font-weight: bold;
			color: #606266;
		}
	}
	
	.chat-list {
		border: 1px solid #EBEEF5;
		border-radius: 4px;
		
		.chat-item {
			display: flex;
			align-items: center;
			padding: 10px 15px;
			cursor: pointer;
			transition: background-color 0.3s;
			
			&:hover {
				background-color: #F5F7FA;
			}
			
			.chat-info {
				flex: 1;
				margin-left: 10px;
				overflow: hidden;
				
				.chat-name {
					font-size: 14px;
					font-weight: 500;
					color: #303133;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}
		}
		
		.empty-data {
			padding: 20px;
			text-align: center;
			color: #909399;
		}
	}
}
</style>

<style>
/* 全局样式确保对话框显示在最上层 */
.el-dialog {
  z-index: 9999 !important;
}
.el-dialog__wrapper {
  z-index: 9998 !important;
}
.v-modal {
  z-index: 9997 !important;
}

/* 调试指示器 */
.debug-indicator {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background-color: #67c23a;
  color: white;
  padding: 10px;
  border-radius: 4px;
  z-index: 10000;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>